package net.pws.common.persistence.hibernate3.utils;

import java.util.Iterator;
import java.util.Map;

public abstract class SQLBuilder {
    
    public static String buildInsertStatement(String tableName,
                                              String idName,
                                              Map columns) {
        StringBuilder part1 = new StringBuilder("insert into ");
        part1.append(tableName).append("( ");
        part1.append(idName).append(",");
        StringBuilder part2 = new StringBuilder(" values ").append("(");
        part2.append(":" + idName + ",");
        int counter = 0;
        int size = columns.keySet().size();
        for (Iterator iter = columns.keySet().iterator(); iter.hasNext(); counter++) {
            String key = (String) iter.next();
            part1.append(key);
            part2.append(":").append(key);
            if (counter != size - 1) {
                part1.append(",");
                part2.append(",");
            }
        }
        
        part1.append(")");
        part2.append(")");
        
        return part1.append(part2).toString();
    }
    
    public static String buildUpdateStatement(String tableName,
                                              String idName,
                                              Map columns) {
        StringBuilder result = new StringBuilder("update ").append(tableName)
                                                           .append(" set ");
        int counter = 0;
        int size = columns.keySet().size();
        for (Iterator iter = columns.keySet().iterator(); iter.hasNext(); counter++) {
            String key = (String) iter.next();
            result.append(key + "=:" + key + " ");
            if (counter != size - 1) {
                result.append(",");
            }
        }
        result.append(" where " + idName + "=:" + idName);
        return result.toString();
    }
    
    public static String buildRemoveStatement(String tableName, String idName) {
        return new StringBuffer("delete from ").append(tableName)
                                               .append(" where ")
                                               .append(idName)
                                               .append("=:")
                                               .append(idName)
                                               .toString();
    }
    
}
